package com.linwen.excise.sort;

/**
 * 归并排序
 *
 * @author : linwen
 * @date : 下午11:08 2021/6/2
 */
public class _05MergeSort {
    public void mergeSort(int[] arr) {
        // merge需要的额外空间
        int[] temp = new int[arr.length];
        //转换成递归需要的格式
        mergeSort(arr, 0, arr.length - 1, temp);
    }

    public void mergeSort(int[] arr, int left, int right, int[] temp) {
        if (left >= right) {
            return;
        }
        int mid = left + (right - left) >> 1;
        //左边merge
        mergeSort(arr, left, mid, temp);
        //右边merge
        mergeSort(arr, mid + 1, right, temp);
        // 整体merge
        mergeSort(arr, left, mid, right, temp);
    }

    private void mergeSort(int[] arr, int left, int mid, int right, int[] temp) {
        //归并需要三个指针，左（起始）  中+1（第二个起始）  额外空间0起始
        int i = left;
        int j = mid + 1;
        int k = 0;

        while (i <= mid && j <= right) {
            temp[k++] = arr[i] <= arr[j] ? arr[i++] : arr[j++];
        }
        while (i <= mid) {
            temp[k++] = arr[i++];
        }
        while (j <= right) {
            temp[k++] = arr[j++];
        }
        k = 0;
        //将temp中的元素全部拷贝到原数组中
        while (left <= right) {
            arr[left++] = temp[k++];
        }
    }
}
